<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>ALPHA BSC 交易量</title>
    <link href="../../resources/layui/css/layui.css" rel="stylesheet">
    <script src="../../resources/js/3.7.1/jquery.min.js"></script>
    <script src="../../resources/layui/layui.js"></script>
</head>
<body style="padding: 20px;">

<div class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">查询日期</label>
        <div class="layui-input-inline">
            <input type="text" name="date" id="date" class="layui-input" value="">
        </div>
        <div class="layui-input-inline">
            <button id="btn-query" class="layui-btn" onclick="startQuery()">开始查询</button>
        </div>
    </div>
</div>

<table class="layui-table" id="resultTable">
    <thead>
    <tr>
        <th>地址</th>
        <th>备注</th>
        <th>交易量</th>
        <th>交易次数</th>
        <th>损耗</th>
        <th>分数</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="resultBody"></tbody>
</table>

<script>
    const API_KEY = "6HQZV977GIY8FNT36XN1JJSE12IP2IYVTQ";
    const TOKEN = "0x55d398326f99059ff775485246999027b3197955"; // USDT
    const DECIMALS = 18;

    const wallets = [
        {name: "涂祥祥", wallet: "0x0ad7d2ba1eef210ec5daabc93e2114348eb71b3d"},
        {name: "北北", wallet: "0x613a93601f31f497e5f2c1f1344f74d69a47f5c8"},
        {name: "涛胜", wallet: "0x280Ad8AB2b308b03Fe901431F2a07F999D7E17e0"},
        {name: "涂昌", wallet: "0x87fcbaed8353d75d2521acbd68ed2d69d723bbb2"},
        {name: "江志华", wallet: "0xeB6f1404C4fdaB45F9D5d894f6D665c83369eFdC"},
        {name: "涂倩", wallet: "0x4b3fEDD724AB4D8772ffdE1471ACD4F780EA81a7"},
    ];
    const form = layui.form;
    const table = layui.table;
    const laydate = layui.laydate;
    const layer = layui.layer;
    var bnb_price = 0
    laydate.render({
        elem: '#date',
        type: 'date',
        value: new Date()
    });

    function fetchBNBPrice() {
        $.get("https://api.binance.com/api/v3/ticker/price", {symbol: "BNBUSDT"}, function (data) {
            const price = parseFloat(data.price).toFixed(2);
            // console.log(data)
            bnb_price = price;
        });
    }

    // setInterval(fetchBNBPrice, 10000)
    fetchBNBPrice()

    // 获取区块号
    function getBlockByTimestamp(ts, closest, callback) {
        $.get("https://api.bscscan.com/api", {
            module: 'block',
            action: 'getblocknobytime',
            timestamp: ts,
            closest: closest,
            apikey: API_KEY
        }, res => {
            if (res.status === "1" && res.result && !isNaN(res.result)) {
                callback(parseInt(res.result));
            } else {
                console.error("区块获取失败：", res);
                callback(null);
            }
        });
    }

    // 查询 token 交易
    function getTokenTransfers(wallet, startBlock, endBlock, callback) {
        let page = 1;
        let offset = 1000;
        let total_out = 0;
        let total_in = 0;
        let order_count = 0;
        let txs = [];
        let loss = 0
        if (bnb_price === 0) {
            fetchBNBPrice()
        }

        function getBnbTransfers(){
            $.get("https://api.bscscan.com/api", {
            module: 'account',
            action: 'txlist',
            contractaddress: TOKEN,
            address: wallet,
            startblock: startBlock,
            endblock: endBlock,
            page,
            offset,
            sort: 'asc',
            apikey: API_KEY
        }, res => {
            // console.log(res)
            if (res.status === "1") {
                res.result.forEach(tx => {
                    const value = parseFloat(tx.value) / (10 ** DECIMALS);
                    if (value > 0) {
                        if (tx.from.toLowerCase() === wallet.toLowerCase()) {
                            total_out += value;
                        } else {
                            total_in += value;
                        }

                        order_count++;
                        txs.push({
                            time: new Date(tx.timeStamp * 1000).toLocaleString(),
                            hash: tx.hash,
                            from: tx.from,
                            to: tx.to,
                            value: value.toFixed(2)
                        });
                    }

                });
                loss = (total_in - total_out) * bnb_price
                total_out = total_out * bnb_price
                console.log(loss, total_out, bnb_price)
            }else {
                setTimeout(getBnbTransfers, 500); // 节流防频率限制
            }

        });
        }

        // txlist 查询 bnb tokentx 查询erc20 代币
        function nextPage() {
            $.get("https://api.bscscan.com/api", {
                module: 'account',
                action: 'tokentx',
                contractaddress: TOKEN,
                address: wallet,
                startblock: startBlock,
                endblock: endBlock,
                page,
                offset,
                sort: 'asc',
                apikey: API_KEY
            }, res => {
                // console.log(res)
                if (res.status === "1") {
                    res.result.forEach(tx => {
                        const value = parseFloat(tx.value) / (10 ** DECIMALS);
                        if (tx.from.toLowerCase() === wallet.toLowerCase()) {
                            total_out += value;
                        } else {
                            total_in += value;
                        }

                        order_count++;
                        txs.push({
                            time: new Date(tx.timeStamp * 1000).toLocaleString(),
                            hash: tx.hash,
                            from: tx.from,
                            to: tx.to,
                            value: value.toFixed(2)
                        });
                    });

                    return callback(total_out, order_count, loss + total_out - total_in, txs);
                }

                setTimeout(nextPage, 500); // 节流防频率限制
            });
        }
        // setTimeout(getBnbTransfers, 200)
        getBnbTransfers()
        nextPage();
    }

    // 启动查询
    function startQuery() {
        const date = document.getElementById("date").value;
        if (!date) return alert("请填写日期");

        const now = Math.floor(Date.now() / 1000);
        const dayStart = Math.floor(new Date(date + " 00:00:00").getTime() / 1000);
        let dayEnd = dayStart + 86400;
        if (dayEnd > now) dayEnd = now;

        $("#btn-query").addClass('layui-btn-disabled').attr('disabled', 'disabled').text('查询中..');
        getBlockByTimestamp(dayStart, 'after', startBlock => {
            getBlockByTimestamp(dayEnd, 'before', endBlock => {
                if (!startBlock || !endBlock) {
                    return alert("区块获取失败");
                }

                let html = '';
                let completed = 0;

                wallets.forEach((w, index) => {
                    setTimeout(function () {
                        getTokenTransfers(w.wallet, startBlock, endBlock, (totalOut, txCount, less, txList) => {
                            const score = Math.floor(Math.log2(totalOut * 2));
                            html += `
            <tr>
              <td>${w.wallet}</td>
              <td>${w.name}</td>
              <td>${totalOut.toFixed(2) * 2}</td>
              <td>${txCount}</td>
              <td>${less}</td>
              <td>${score}</td>
              <td><button class="layui-btn layui-btn-xs" onclick='showDetails(${JSON.stringify(txList)})'>查看详情</button></td>
            </tr>
          `;
                            completed++;
                            $("#btn-query").removeClass("layui-btn-disabled").prop("disabled", false).text('开始查询');
                            $("#resultBody").html(html);
                        });
                    }, 200)

                });
            });
        });
    }

    // 显示详细信息
    function showDetails(data) {
        let html = `<table class="layui-table"><thead><tr><th>时间</th><th>hash</th><th>From</th><th>To</th><th>金额</th></tr></thead><tbody>`;
        data.forEach(tx => {
            html += `<tr><td>${tx.time}</td><td>${tx.hash}</td><td>${tx.from}</td><td>${tx.to}</td><td>${tx.value}</td></tr>`;
        });
        html += `</tbody></table>`;

        layer.open({
            type: 1,
            area: ['700px', '500px'],
            title: '交易详情',
            content: html,
            shadeClose: true
        });
    }
</script>

</body>
</html>
